using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ProgNetComponentsDx.Controls;

namespace ProgNetComponentsDx.Forms
{
    public partial class FormBackgroundWorkBase : XtraForm
    {
        public virtual BackgroundControlBase BackgroundControl
        {
            get { return null; }
        }

        protected bool _CanClose = false;
        protected bool _Loaded;

        [Category(ProgNetComponents.Constants.Categories.ProgNetSettings)]
        public bool CloseOnComplete
        {
            get;
            set;
        }
        
        public FormBackgroundWorkBase()
        {
            InitializeComponent();
            CloseOnComplete = true;
        }

        public FormBackgroundWorkBase(string text)
            : this()
        {
            this.Text = text;
        }

        public event ProgressChangedEventHandler ProgressChanged
        {
            add { this.BackgroundControl.ProgressChanged += value; }
            remove { this.BackgroundControl.ProgressChanged -= value; }
        }
        public event RunWorkerCompletedEventHandler RunWorkerCompleted
        {
            add { this.BackgroundControl.RunWorkerCompleted += value; }
            remove { this.BackgroundControl.RunWorkerCompleted -= value; }
        }
        public event EventHandler Canceling
        {
            add { this.BackgroundControl.Canceling += value; }
            remove { this.BackgroundControl.Canceling -= value; }
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            if (!_CanClose)
                e.Cancel = true;
            else
                DialogResult = DialogResult.OK;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            _CanClose = false;
            if (!this.IsDesignMode())
            {
                BackgroundControl.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundControl_RunWorkerCompleted);

                _Loaded = true;
                BackgroundControl.Start();
            }
        }

        void BackgroundControl_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            _CanClose = true;
            Close();
        }
    }
}